package com.arong.swing.db.dao;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import com.arong.swing.db.JDBCUtils;
import com.arong.swing.util.UUIDUtils;

/**
 * 所有DAO的基类
 */
public abstract class BaseDAO {
	/** 存放本地的布控人员信息数据 ,不再启用，采用分解文件的方式*/
	//public static final String DB_PACKAGEDATA = "./datas/packageData.db";
	
	/** 存放本地的核查记录相关数据 */
	public static final String DB_CHECKRECORD = "./datas/checkRecord.db";
	/** 用于上传存放本地的核查记录的备份数据 */
	public static final String DB_CHECKRECORDUPLOAD = "./datas/checkRecordUpload.db";
	
	/** 用于上传存放本地的设备活动记录相关数据 */
	public static final String DB_DEVRECORDUPLOAD = "./datas/devRecordUpload.db";
	/** 存放本地的设备、用户、最新包版本及接收记录 */
	public static final String DB_ANRONGTEC = "./datas/anrongtec.db";
	
	protected JDBCUtils jdbcUtils=null;
	
	public BaseDAO(String dbFile){
		this.jdbcUtils = new JDBCUtils(dbFile);
		checkTabbleIsExist();
	}
	public BaseDAO(JDBCUtils jdbcUtils){
		this.jdbcUtils = jdbcUtils;
		checkTabbleIsExist();
	}
	public abstract String getCreateTableSql();
	
	public void checkTabbleIsExist(){
		try {
			String tableSql = getCreateTableSql();
			if(tableSql !=null && tableSql.length() > 0){
				jdbcUtils.execute(getCreateTableSql());
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public int batchCommit(IBatchDeal batchDeal) throws Exception {
		int i=0;
		Connection conn = null;
		try {
			conn = jdbcUtils.getConnection();
			conn.setAutoCommit(false);
			i= batchDeal.doBatchDeal(conn);
		 	conn.commit();
		} catch (Exception e) {
			if(conn != null){
				try {
					conn.rollback();
				} catch (SQLException e1) {
					e1.printStackTrace();
					throw new Exception("rollback error", e);
				}
			}
			throw new Exception("add error", e);
		}finally{
			try {
				conn.setAutoCommit(true);
				jdbcUtils.closeConn(conn);
			} catch (SQLException e) {
				e.printStackTrace();
				throw new Exception("closeConn error", e);
			}
		}
		return i;
	}
	
	/**
	 * 把List对象拷贝到 Object 对象中
	 * 
	 * @param qryList
	 * @return
	 * @author hsy
	 */
	public Object[] setQryList(List<Object> qryList) {
		Object[] obj = null;
		if (qryList != null && qryList.size() > 0) {
			obj = new Object[qryList.size()];
			for (int i = 0; i < qryList.size(); i++) {
				obj[i] = qryList.get(i);
			}
		}
		return obj;
	}
	public String getSeqValue() {
		return UUIDUtils.uuid32();
	}
}